package com.jsb.controller;


import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import com.annotation.SystemControllerLog;
import com.jsb.common.config.Const;
import com.jsb.common.config.Global;
import com.jsb.common.utils.JsonUtil;
import com.jsb.common.utils.StringUtils;
import com.jsb.dto.QstAnsAdmin;
import com.jsb.dto.UserAnswer;
import com.jsb.model.Admin;
import com.jsb.model.Answer;
import com.jsb.model.AnswerExample;
import com.jsb.model.AnswerExample.Criteria;
import com.jsb.model.Question;
import com.jsb.model.User;
import com.jsb.model.UserExample;
import com.jsb.service.AdminService;
import com.jsb.service.AnswerService;
import com.jsb.service.QuestionService;
import com.jsb.service.UserService;

@Controller
public class AnswerController{
	
	private int defaultPageSize=10;
	
	private String redirect = "redirect:/answer/list.do";
	
	@Resource
	private AnswerService answerService;
	
	@Resource
	private QuestionService questionService;
	
	@Resource
	private AdminService adminService;
	@Resource
	private UserService userService;
	
	@RequestMapping("/answer/list")
	public String list(
			Model model,String uuid,String qid,
			String phoneNumber,String status,String delFlag,
			@RequestParam(value = "pageNum", required = false) Integer pageNum,
			@RequestParam(value = "pageSize", required = false) Integer pageSize) {
		int maxPageNum = 0;
		if (pageSize == null) {
			pageSize = defaultPageSize;
		}
		AnswerExample answerExample = new AnswerExample();
		List<User> userByLikePhone = userService.getUserByLikePhone(phoneNumber);
		if(StringUtils.isEmpty(phoneNumber)){
			Criteria criteria = answerExample.createCriteria();
			if(StringUtils.isNotEmpty(status)){
				criteria.andStatusEqualTo(Integer.valueOf(status));
			}
			if(StringUtils.isNotEmpty(delFlag)){
				criteria.andDelFlagEqualTo(delFlag);
			}
			if(StringUtils.isNotEmpty(uuid)){
				criteria.andUuidEqualTo(uuid);
			}
			if(StringUtils.isNotEmpty(qid)){
				criteria.andQuestionUuidEqualTo(qid);
			}
		}else{
			for (User user : userByLikePhone) {
				String userid = user.getPhoneNumber();
				Criteria criteria = answerExample.createCriteria();
				if(StringUtils.isNotEmpty(userid)){
					criteria.andPhoneNumberLike("%"+userid+"%");
				}
				if(StringUtils.isNotEmpty(status)){
					criteria.andStatusEqualTo(Integer.valueOf(status));
				}
				if(StringUtils.isNotEmpty(delFlag)){
					criteria.andDelFlagEqualTo(delFlag);
				}
				if(StringUtils.isNotEmpty(uuid)){
					criteria.andUuidEqualTo(uuid);
				}
				if(StringUtils.isNotEmpty(qid)){
					criteria.andQuestionUuidEqualTo(qid);
				}
				answerExample.or(criteria);
			}
		}
		answerExample.setOrderByClause(" date DESC");
		int totalCount = answerService.countAnswer(answerExample);
		if(totalCount%pageSize == 0){
			maxPageNum = totalCount/pageSize;
		}else{
			maxPageNum = totalCount/pageSize+1;
		}
		if (pageNum == null || pageNum < 1) {
			pageNum = 1;
		}else {
			if(maxPageNum > 0 && pageNum > maxPageNum) {
				pageNum = maxPageNum;
			}
		}
		answerExample.setPageIndex((pageNum - 1) * pageSize);
		answerExample.setPageSize(pageSize);
		List<Answer> answers = answerService.getPageAnswer(answerExample);
		List<QstAnsAdmin> qstAnsAdmins = new ArrayList<QstAnsAdmin>();
		for (Answer answer : answers) {
			QstAnsAdmin qstAnsAdmin = new QstAnsAdmin();
			Question questionByUuid = questionService.getQuestionByUuid(answer.getQuestionUuid());
			Admin adminById = adminService.getAdminById(answer.getAuditor());
			User userByPhoneNumber = userService.getUserByPhoneNumber(answer.getPhoneNumber());
			qstAnsAdmin.setAdmin(adminById);
			qstAnsAdmin.setAnswer(answer);
			qstAnsAdmin.setQuestion(questionByUuid);
			qstAnsAdmin.setUser(userByPhoneNumber);
			qstAnsAdmins.add(qstAnsAdmin);
		}
		model.addAttribute("totalCount", totalCount);
		model.addAttribute("pageNum", pageNum);
		model.addAttribute("pageSize", pageSize);
		if(totalCount%pageSize == 0){
			model.addAttribute("maxPageNum", totalCount/pageSize);
		}else{
			model.addAttribute("maxPageNum", totalCount/pageSize+1);
		}
		model.addAttribute("phoneNumber", phoneNumber);
		model.addAttribute("status", status);
		model.addAttribute("delFlag", delFlag);
		model.addAttribute("qid", qid);
		model.addAttribute("qstAnsAdmins", qstAnsAdmins);
		return "/Answer/list";
	}
	/**
	 * 举报通过
	 * @param model
	 * @param request
	 * @param uuid
	 * @return
	 */
	@RequestMapping("/answer/passreport")
	public String passreport(Model model,HttpServletRequest request,
			@RequestParam(value = "uuid", required = true) String uuid){
		Map<String,String> map = new HashMap<String, String>();
		Admin admin = (Admin) request.getSession().getAttribute("loginUser");
		String id = admin.getId();
		Answer answerByUuid = answerService.getAnswerByUuid(uuid);
		String status = answerByUuid.getStatus().toString();
		if(status.equals(Const.PASSREPORT)){
			map.put("status", Global.FALSE);
			map.put("info", "该条回答已经审核过，同意举报！");
			model.addAttribute("json", JsonUtil.toJson(map));
			return "/json";
		}
		if(status.equals(Const.NOPASSREPORT)){
			map.put("status", Global.FALSE);
			map.put("info", "该条回答已经审核过，驳回举报！");
			model.addAttribute("json", JsonUtil.toJson(map));
			return "/json";
		}
		if(status.equals(Const.REPORTED)){
			String res = answerService.passReport(uuid,id);
			model.addAttribute("json", res);
			return "/json";
		}else{
			map.put("status", Global.FALSE);
			map.put("info", "该条回答未被举报");
			model.addAttribute("json", JsonUtil.toJson(map));
			return "/json";
		}
	}
	/**
	 * 驳回举报
	 * @param model
	 * @param request
	 * @param uuid
	 * @return
	 */
	@RequestMapping("/answer/nopassreport")
	public String nopassreport(Model model,HttpServletRequest request,
			@RequestParam(value = "uuid", required = true) String uuid){
		Map<String,String> map = new HashMap<String, String>();
		Admin admin = (Admin) request.getSession().getAttribute("loginUser");
		String id = admin.getId();
		Answer answerByUuid = answerService.getAnswerByUuid(uuid);
		String status = answerByUuid.getStatus().toString();
		if(status.equals(Const.PASSREPORT)){
			map.put("status", Global.FALSE);
			map.put("info", "该条回答已经审核过，同意举报！");
			model.addAttribute("json", JsonUtil.toJson(map));
			return "/json";
		}
		if(status.equals(Const.NOPASSREPORT)){
			map.put("status", Global.FALSE);
			map.put("info", "该条回答已经审核过，驳回举报！");
			model.addAttribute("json", JsonUtil.toJson(map));
			return "/json";
		}
		if(status.equals(Const.REPORTED)){
			Answer answer = new Answer();
			answer.setUuid(uuid);
			answer.setStatus(Integer.valueOf(Const.NOPASSREPORT));
			answer.setAuditTime(new Date());
			answer.setAuditor(id);
			answerService.updateAnswer(answer);
			map.put("status", Global.TRUE);
			map.put("info", "审核成功");
			model.addAttribute("json", JsonUtil.toJson(map));
			return "/json";
		}else{
			map.put("status", Global.FALSE);
			map.put("info", "该条回答未被举报");
			model.addAttribute("json", JsonUtil.toJson(map));
			return "/json";
		}
	}
	@RequestMapping("/answer/hidden")
	public String hidden(Model model,@RequestParam(value = "uuid", required = true) String uuid ){
		Map<String,String> map = new HashMap<String, String>();
		try {
			answerService.updateHidden(uuid);
			map.put("status", Global.TRUE);
			map.put("info", "修改成功");
			model.addAttribute("json", JsonUtil.toJson(map));
			return "/json";
		} catch (Exception e) {
			map.put("status", Global.FALSE);
			map.put("info", "系统繁忙");
			model.addAttribute("json", JsonUtil.toJson(map));
			return "/json";
		}
	}
	@RequestMapping("/answer/show")
	public String show(Model model,@RequestParam(value = "uuid", required = true) String uuid ){
		Map<String,String> map = new HashMap<String, String>();
		try {
			answerService.updateShow(uuid);
			map.put("status", Global.TRUE);
			map.put("info", "修改成功");
			model.addAttribute("json", JsonUtil.toJson(map));
			return "/json";
		} catch (Exception e) {
			map.put("status", Global.FALSE);
			map.put("info", "系统繁忙");
			model.addAttribute("json", JsonUtil.toJson(map));
			return "/json";
		}
	}
	
	@RequestMapping("/answer/toAdd")
	public String toAdd(Model model) {
		return "/Answer/add";
	}

	@RequestMapping("/answer/add")
	public String add(Model model, @ModelAttribute("answer") Answer answer) {
		answerService.addAnswer(answer);
		return redirect;
	}

	@RequestMapping("/answer/del")
	public String del(Model model,
			@RequestParam(value = "uuid", required = true) String uuid) {
		answerService.delAnswerByUuid(uuid);
		return redirect;
	}

	@RequestMapping("/answer/toEdit")
	public String toEdit(Model model,
			@RequestParam(value = "uuid", required = true) String uuid) {
		Answer answer = answerService.getAnswerByUuid(uuid);
		model.addAttribute("answer", answer);
		return "/Answer/edit";
	}

	@RequestMapping("/answer/edit")
	@SystemControllerLog(description = "审核文章")
	public String edit(Model model, @ModelAttribute("answer") Answer answer) {
		answerService.updateAnswer(answer);
		return redirect;
	}

	@RequestMapping("/answer/view")
	public String view(Model model,
			@RequestParam(value = "uuid", required = true) String uuid) {
		Answer answer = answerService.getAnswerByUuid(uuid);
		String auditor = answer.getAuditor();
		Admin admin = adminService.getAdminById(auditor);
		String questionUuid = answer.getQuestionUuid();
		Question question = questionService.getQuestionByUuid(questionUuid);
		QstAnsAdmin qstAnsAdmin = new QstAnsAdmin();
		qstAnsAdmin.setAnswer(answer);
		qstAnsAdmin.setQuestion(question);
		qstAnsAdmin.setAdmin(admin);
		model.addAttribute("qstAnsAdmin", qstAnsAdmin);
		return "/Answer/view";
	}
	@RequestMapping("/answer/reportList")
	public String reportList(
			Model model,String phoneNumber,
			@RequestParam(value = "pageNum", required = false) Integer pageNum,
			@RequestParam(value = "pageSize", required = false) Integer pageSize) {
		int maxPageNum = 0;
		if (pageSize == null) {
			pageSize = defaultPageSize;
		}
		AnswerExample answerExample = new AnswerExample();
		Criteria criteria = answerExample.createCriteria();
		criteria.andStatusEqualTo(Integer.valueOf(Const.PASSREPORT));
		if(StringUtils.isNotBlank(phoneNumber)){
			criteria.andPhoneNumberLike("%"+phoneNumber+"%");
		}
		int totalCount = answerService.countAnswer(answerExample);
		if(totalCount%pageSize == 0){
			maxPageNum = totalCount/pageSize;
		}else{
			maxPageNum = totalCount/pageSize+1;
		}
		if (pageNum == null || pageNum < 1) {
			pageNum = 1;
		}else {
			if(maxPageNum > 0 && pageNum > maxPageNum) {
				pageNum = maxPageNum;
			}
		}
		answerExample.setPageIndex((pageNum - 1) * pageSize);
		answerExample.setPageSize(pageSize);
		List<Answer> answers = answerService.selectByExample(answerExample);
		List<UserAnswer> userAnswers= new ArrayList<UserAnswer>();
		for (Answer answer : answers) {
			String phone = answer.getPhoneNumber();
			User user = userService.getUserByPhoneNumber(phone);
			UserAnswer userAnswer = new UserAnswer();
			userAnswer.setUser(user);
			if(!userAnswers.contains(userAnswer)){
				userAnswers.add(userAnswer);
			}
		}
		if(null != userAnswers && userAnswers.size()>0){
			for (UserAnswer userAnswer : userAnswers) {
				String phone2 = userAnswer.getUser().getPhoneNumber();
				AnswerExample answerExample2 = new AnswerExample();
				Criteria criteria2 = answerExample2.createCriteria();
				criteria2.andPhoneNumberEqualTo(phone2);
				int count = answerService.countAnswer(answerExample2);
				userAnswer.setCount(count);
			}
		}
		
		
		model.addAttribute("totalCount", totalCount);
		model.addAttribute("pageNum", pageNum);
		model.addAttribute("pageSize", pageSize);
		if(totalCount%pageSize == 0){
			model.addAttribute("maxPageNum", totalCount/pageSize);
		}else{
			model.addAttribute("maxPageNum", totalCount/pageSize+1);
		}
		model.addAttribute("userAnswers", userAnswers);
		model.addAttribute("phoneNumber", phoneNumber);
		return "/Answer/reportList";
	}
	/**
	 * 某人的举报详情列表
	 * @param model
	 * @param phoneNumber
	 * @param status
	 * @param delFlag
	 * @param pageNum
	 * @param pageSize
	 * @return
	 */
	@RequestMapping("/answer/reportListDetail")
	public String reportListDetail(
			Model model,String phone,
			@RequestParam(value = "pageNum", required = false) Integer pageNum,
			@RequestParam(value = "pageSize", required = false) Integer pageSize) {
		int maxPageNum = 0;
		if (pageSize == null) {
			pageSize = defaultPageSize;
		}
		AnswerExample answerExample = new AnswerExample();
		Criteria criteria = answerExample.createCriteria();
		criteria.andPhoneNumberEqualTo(phone);
		criteria.andStatusEqualTo(Global.Answer_status_four);//举报通过
		int totalCount = answerService.countAnswer(answerExample);
		if(totalCount%pageSize == 0){
			maxPageNum = totalCount/pageSize;
		}else{
			maxPageNum = totalCount/pageSize+1;
		}
		if (pageNum == null || pageNum < 1) {
			pageNum = 1;
		}else {
			if(maxPageNum > 0 && pageNum > maxPageNum) {
				pageNum = maxPageNum;
			}
		}
		answerExample.setPageIndex((pageNum - 1) * pageSize);
		answerExample.setPageSize(pageSize);
		List<Answer> answers = answerService.getPageAnswer(answerExample);
		List<QstAnsAdmin> qstAnsAdmins = new ArrayList<QstAnsAdmin>();
		for (Answer answer : answers) {
			QstAnsAdmin qstAnsAdmin = new QstAnsAdmin();
			Question questionByUuid = questionService.getQuestionByUuid(answer.getQuestionUuid());
			Admin adminById = adminService.getAdminById(answer.getAuditor());
			qstAnsAdmin.setAdmin(adminById);
			qstAnsAdmin.setAnswer(answer);
			qstAnsAdmin.setQuestion(questionByUuid);
			qstAnsAdmins.add(qstAnsAdmin);
		}
		model.addAttribute("totalCount", totalCount);
		model.addAttribute("pageNum", pageNum);
		model.addAttribute("pageSize", pageSize);
		if(totalCount%pageSize == 0){
			model.addAttribute("maxPageNum", totalCount/pageSize);
		}else{
			model.addAttribute("maxPageNum", totalCount/pageSize+1);
		}
		
		model.addAttribute("qstAnsAdmins", qstAnsAdmins);
		return "/Answer/reportListDetail";
	}
}
